import { set } from 'lodash';
// 全局共享数据示例
import { DEFAULT_NAME } from '@/constants';
import { getNoticeNum } from '@/services/commonServices';
import { getUerInfo, setUserInfoLocal } from '@/utils/info';
import { useState } from 'react';
import { useRequest } from 'ahooks';

const useGlobal = () => {
  const [name, setName] = useState<string>(DEFAULT_NAME);
  const [menuShow,setMenuShow] = useState<boolean>(true);
  const [showLogin,setShowLogin]= useState<boolean>(false);
  const [userInfo,setUserInfo] = useState<API.UserInfo>(getUerInfo()||{});
  const [noticeNum,setNoticeNum] = useState({
    followCount:0,
    likeCount:0,
    favoritesCount:0,
    commentCount:0,
    totalCount:0,
  });
  const [followList,setFollowList] = useState([]); //


  //设置用户信息
  const changeUserInfo = (info:API.UserInfo) =>{
    setUserInfoLocal(info);
    setUserInfo(info);
  }
  const changeNoticeNum = (countObj) =>{
    setNoticeNum({
      ...(countObj||{}),
      totalCount:Object.values(countObj).reduce((result:number,item:number)=>{
        result+=Number(item)
        return result
      },0),
    })
  }
  useRequest(()=>{
    if(!userInfo.id)return {
      followCount:0,
      likeCount:0,
      favoritesCount:0,
      commentCount:0,
    }
    return getNoticeNum()
  },{ //轮询请求通知
    pollingInterval: 20000,
    onSuccess: (res) => {
      changeNoticeNum(res)
    }
  })
  return {
    name,
    setName,
    menuShow,
    setMenuShow,
    showLogin,
    setShowLogin,
    userInfo,
    changeUserInfo,
    noticeNum,
    setNoticeNum,
    changeNoticeNum,
  };
};

export default useGlobal;
